﻿using SkiaSharp;
using UtilsBase;

namespace GatewayServer.Common
{
    public static class ImageHelper
    {
        /// <summary>
        /// 创建图像的缩略图。使用SkiaSharp，以支持跨平台。
        /// </summary>
        /// <param name="orgPath">原图文件全路径</param>
        /// <param name="thuPath">将生成的缩略图文件全路径</param>
        public static void MakeThumb(string orgPath, string thuPath, int width, int height)
        {

            //const int width = 180, height = 135;
            const int quality = 100; //质量为[SKFilterQuality.Medium]结果的100%
            using var input = File.OpenRead(orgPath);
            using var inputStream = new SKManagedStream(input);
            using var original = SKBitmap.Decode(inputStream);

            int toheight = original.Height;
            int towidth = original.Width;



            if (toheight > towidth)
            {
                if (toheight > height)
                {
                    toheight = height;
                }
                towidth = int.Parse(UtilsNumber.GetNumberForLength(original.Width * (height / (original.Height * 1.0)), 0).ToString());
            }
            else if (towidth > width)
            {
                if (towidth > width)
                {
                    towidth = width;
                }
                toheight = int.Parse(UtilsNumber.GetNumberForLength(original.Height * (width / (original.Width * 1.0)), 0).ToString());
            }





            //if (original.Width <= width && original.Height <= height)//如果宽度和高度都小于缩率图值，则直接复制文件
            //{
            //    File.Copy(orgPath, thuPath);
            //}
            //else
            //{
            using (var resized = original.Resize(new SKImageInfo(towidth, toheight), SKFilterQuality.Medium))
            {
                if (resized != null)
                {
                    using var image = SKImage.FromBitmap(resized);
                    using var output = File.OpenWrite(thuPath);
                    image.Encode(SKEncodedImageFormat.Png, quality).SaveTo(output);
                    image.Dispose();
                }
            }
            input.Close();
            inputStream.Dispose();
            original.Dispose();
            // }
        }

    }
}
